package com.example.modulepicselector.internal.model;

import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.Loader;

import com.example.modulepicselector.internal.loader.PicLoader;

import org.jetbrains.annotations.NotNull;

import java.lang.ref.WeakReference;

public class PicCollection implements LoaderManager.LoaderCallbacks<Cursor> {

    private WeakReference<Context> mContext;
    private LoaderManager mLoaderManager;
    private boolean mLoadFinished;
    private static final int LOADER_ID = 1;
    private PicCallbacks mCallbacks;
    private int mCurrentSelection;
    private static final String STATE_CURRENT_SELECTION = "state_current_selection";

    @NonNull
    @NotNull
    @Override
    public Loader<Cursor> onCreateLoader(int id, @Nullable @org.jetbrains.annotations.Nullable Bundle args) {
        Context context = mContext.get();
        if (context == null) {
            return null;
        }
        mLoadFinished = false;

        return PicLoader.newInstance(context);
    }

    @Override
    public void onLoadFinished(@NonNull @NotNull Loader<Cursor> loader, Cursor data) {

        Context context = mContext.get();
        if (context == null) {
            return;
        }
        if (!mLoadFinished) {

            mLoadFinished = true;

            mCallbacks.onPicLoad(data);

        }

    }

    @Override
    public void onLoaderReset(@NonNull @NotNull Loader<Cursor> loader) {
        Context context = mContext.get();
        if (context == null) {
            return;
        }

        mCallbacks.onPicReset();
    }


    public void onCreate(FragmentActivity activity, PicCallbacks callbacks) {
        mContext = new WeakReference<Context>(activity);
        mLoaderManager = activity.getSupportLoaderManager();
        mCallbacks = callbacks;
    }

    public void onRestoreInstanceState(Bundle savedInstanceState) {
        if (savedInstanceState == null) {
            return;
        }

        mCurrentSelection = savedInstanceState.getInt(STATE_CURRENT_SELECTION);
    }

    public void onSaveInstanceState(Bundle outState) {
        outState.putInt(STATE_CURRENT_SELECTION, mCurrentSelection);
    }

    public void onDestroy() {
        if (mLoaderManager != null) {
            mLoaderManager.destroyLoader(LOADER_ID);
        }
        mCallbacks = null;
    }

    public void loadPic() {
        mLoaderManager.initLoader(LOADER_ID, null, this);
    }

    public int getCurrentSelection() {
        return mCurrentSelection;
    }

    public void setStateCurrentSelection(int currentSelection) {
        mCurrentSelection = currentSelection;
    }


    public interface PicCallbacks {
        void onPicLoad(Cursor cursor);

        void onPicReset();
    }
}
